package team.seekers.catering.food.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import team.seekers.catering.common.enums.DRIsEnum;
import team.seekers.catering.food.entity.dto.query.FoodQuery;
import team.seekers.catering.food.entity.pojo.ContainFoodListDTO;
import team.seekers.catering.food.entity.pojo.ContainIngredientListDTO;
import team.seekers.catering.food.entity.dao.Food;
import team.seekers.catering.food.entity.dto.update.FoodUpdateDTO;
import team.seekers.catering.food.entity.pojo.ContainNutrimentListDO;
import team.seekers.catering.food.entity.vo.info.FoodInfoVO;
import team.seekers.catering.food.entity.pojo.ContainIngredientListVO;
import team.seekers.catering.food.entity.vo.list.FoodListVO;
import team.seekers.catering.food.entity.pojo.ContainNutrimentListVO;
import team.seekers.catering.food.entity.dto.add.ComboAddDTO;
import team.seekers.catering.food.entity.dto.add.FoodAddDTO;
import team.seekers.catering.food.mapper.FoodMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import team.seekers.catering.user.service.UserService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 食物表 服务实现类
 * </p>
 *
 * @author hbc
 * @since 2022-02-04
 */
@Service
public class FoodService extends ServiceImpl<FoodMapper, Food>{

    @Autowired
    private IngredientService ingredientService;

    @Autowired
    private UserService userService;

    public Map<String, Object> adminPageOrder(long current, long limit, FoodQuery query) {
        QueryWrapper<Food> wrapper = new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(query.getNameKey())){
            wrapper.like("name",query.getNameKey());
        }
        Page<Food> page = new Page<>(current,limit);
        wrapper.orderByDesc("gmt_create");
        page(page,wrapper);
        Long total = page.getTotal();
        if(page.getRecords() == null){
            return null;
        }
        System.out.println("获取的记录是"+page.getRecords());

        List<FoodListVO> list = new ArrayList<>();
        for (Food record : page.getRecords()) {
            FoodListVO vo = new FoodListVO();
            BeanUtils.copyProperties(record,vo);
            list.add(vo);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("rows",list);
        return map;
    }

    public String add(FoodAddDTO foodAddDTO) {
        Food food = new Food();
        BeanUtils.copyProperties(foodAddDTO,food);
        food.setIngredientContent(JSON.toJSONString(foodAddDTO.getIngredientContent()));
        food.setNrv(JSON.toJSONString(foodAddDTO.getNrv()));
        save(food);
        return food.getId();
    }

    public FoodInfoVO get(String id) {

        Food food = getById(id);

        return foodToVO(food);
    }

    public String update(FoodUpdateDTO foodUpdateDTO) {
        Food food = new Food();
        BeanUtils.copyProperties(foodUpdateDTO,food);
        food.setIngredientContent(JSON.toJSONString(foodUpdateDTO.getIngredientContent()));
        food.setNrv(JSON.toJSONString(foodUpdateDTO.getNrv()));
        updateById(food);
        return food.getId();
    }


    public boolean isExist(String foodId) {
        return getById(foodId) != null;
    }

    /**
     * 解析套餐组成，算出套餐成分
     * @param comboAddDTO
     */
    public void setParamFromList(ComboAddDTO comboAddDTO) {
        // 食材统计
        ArrayList<ContainIngredientListDTO> ingredientList = new ArrayList<>();
        for (ContainFoodListDTO containFoodListDTO : comboAddDTO.getContent()) {
            Food food = getById(containFoodListDTO.getId());

            List<ContainIngredientListDTO> containIngredientListDTOS = JSONObject.parseArray(food.getIngredientContent(), ContainIngredientListDTO.class);
            for (ContainIngredientListDTO containIngredientListDTO : containIngredientListDTOS) {
                boolean isExit = false;
                for (ContainIngredientListDTO listPA : ingredientList) {
                    if(listPA.getId() == containIngredientListDTO.getId()){
                        isExit = true;
                        listPA.setAmount(listPA.getAmount()+ containIngredientListDTO.getAmount());
                    }
                }
                if(!isExit){
                    ingredientList.add(containIngredientListDTO);
                }
            }
        }
        comboAddDTO.setIngredientContent(ingredientList);
        ingredientService.setParamFromList(comboAddDTO);

    }

    public FoodInfoVO foodToVO(Food food){
        FoodInfoVO foodInfoVO = new FoodInfoVO();

        if (food == null){
            return null;
        }
        BeanUtils.copyProperties(food,foodInfoVO);

        ArrayList<ContainNutrimentListVO> containNutrimentListVOS = new ArrayList<>();
        if(food.getNrv() != null){
            List<ContainNutrimentListDO> containNutrimentListDOS = JSONObject.parseArray(food.getNrv(), ContainNutrimentListDO.class);
            for (ContainNutrimentListDO containNutrimentListDO : containNutrimentListDOS) {
                containNutrimentListVOS.add(new ContainNutrimentListVO(
                        DRIsEnum.getByValue(containNutrimentListDO.getNutrimentId()).getName(),
                        containNutrimentListDO.getAmount()+" "+DRIsEnum.getByValue(containNutrimentListDO.getNutrimentId()).getUnit().split("/")[0],
                        new BigDecimal(containNutrimentListDO.getNutrimentContent()).multiply(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_HALF_UP).toString()
                ));
            }
        }


        ArrayList<ContainIngredientListVO> containIngredientListVOS = new ArrayList<>();
        if(food.getIngredientContent() != null){
            List<ContainIngredientListDTO> containIngredientListDTOS = JSONObject.parseArray(food.getIngredientContent(), ContainIngredientListDTO.class);
            for (ContainIngredientListDTO containIngredientListDTO : containIngredientListDTOS) {
                containIngredientListVOS.add(new ContainIngredientListVO(
                        containIngredientListDTO.getId(),
                        ingredientService.getById(containIngredientListDTO.getId()).getNcName(),
                        containIngredientListDTO.getAmount()
                ));
            }
        }

        foodInfoVO.setNrv(containNutrimentListVOS);
        foodInfoVO.setIngredientContent(containIngredientListVOS);
        return foodInfoVO;
    }
}
